/* eslint no-useless-escape:0 import/prefer-default-export:0 */

const reg =
  /(((^https?:(?:\/\/)?)(?:[-;:&=\+\$,\w]+@)?[A-Za-z0-9.-]+(?::\d+)?|(?:www.|[-;:&=\+\$,\w]+@)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%@.\w_]*)#?(?:[\w]*))?)$/;

export const isUrl = (path: string): boolean => reg.test(path);

// 处理 ant-design 的分页参数，保持与后端格式一致
export const transformParams = (
  params?: API.PageParams,
  sorter?: Record<string, any>,
  filter?: Record<string, any>,
): Struct.RequestParams => {
  const filterParams = {};
  if (filter) {
    Object.keys(filter).forEach((key) => {
      filterParams[key] = filter[key]?.join(',');
    });
  }
  const result: Struct.RequestParams = {
    ...params,
    ...filterParams,
    page: params?.current || undefined,
    size: params?.pageSize || undefined,
    sort: undefined,
  };
  delete result.current;
  delete result.pageSize;
  if (sorter) {
    const strings = Object.keys(sorter).map((key) => `${key},${sorter[key].replace('end', '')}`);
    result.sort = strings[0] || undefined;
  }
  return result;
};

// 把后端返回的分页数据转换成 ProTable 所需要的数据格式
export const transformProTableData = (page: Struct.PageResponse<any>) => {
  return {
    data: page.list,
    // success 请返回 true，不然 table 会停止解析数据，即使有数据
    success: true,
    // 不传会使用 data 的长度，如果是分页一定要传
    total: page.total,
  };
};

// 判断一个页面的 props 中是否存在子路由需要展示，如果存在子路由需要展示，则应该直接展示子路由，而不是一直展示当前页面
export const hasRouteChildren = (pageProps: any) => {
  // console.log('props', pageProps?.match?.isExact, pageProps)
  return !pageProps?.match?.isExact && pageProps.children;
};
